﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ArchivingDataModel;
using ArchivingDataWebForms.Helpers;
using Telerik.Web.UI;
using System.Collections;
using ArchivingDataModel.Enums;
using TelerikHelper;

namespace ArchivingDataWebForms.Pages.FilesTypes
{
    public partial class ViewFilesTypes : WebFormBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }


        protected void AdvancedRadGridResults_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (!e.IsFromDetailTable)
                    {
                        var items = ent.FilesTypes.ToArray();
                        this.AdvancedRadGridResults.DataSource = items;
                    }
                }
            }
            catch(Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                //e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_DetailTableDataBind(object sender, GridDetailTableDataBindEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridDataItem dataItem = (GridDataItem)e.DetailTableView.ParentItem;
                    if (e.DetailTableView.Name == "CustomFields")
                    {
                        long id = Convert.ToInt64(dataItem.GetDataKeyValue("FileType_ID"));
                        var cusFields = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == id).Select(i => new { i.CusField.CusField_ID, i.FilesType.FileType_ID, i.CusFieldLabel_Ar, i.CusFieldLabel_En, i.CusFieldNote_Ar, i.CusFieldNote_En, i.FT_CS_Code, i.FT_CS_ID, CFieldTypeName_Ar = i.CusField.CusFieldsType.CFieldTypeName_Ar,i.DateMaxValue,i.DateMinValue,i.NumberDecimalPlaces,i.NumberMaxValue,i.NumberMinValue,i.RegExp_AR,i.RegExp_EN,i.RegExpMessage_AR,i.RegExpMessage_EN, i.RequiredMessage_AR, i.RequiredMessage_EN, i.CusField_Order }).OrderBy(i => i.CusField_Order).ToArray();
                        e.DetailTableView.DataSource = cusFields;
                    }
                    else if (e.DetailTableView.Name == "PreValues")
                    {
                        long id = Convert.ToInt64(dataItem.GetDataKeyValue("FT_CS_ID"));
                        var prevalues = ent.PreValues.Where(i => i.FilesTypes_CusFields.FT_CS_ID == id).Select(i => new { i.PreValue_ID, i.FilesTypes_CusFields.FT_CS_ID, i.PreValueName_Ar, i.PreValueName_En, i.PreValueNote_Ar, i.PreValueNote_En, i.PreValue_Code ,i.PreValue_Order,i.IsSelected}).OrderBy(i=>i.PreValue_Order).ToArray();
                        e.DetailTableView.DataSource = prevalues;
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                //e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    //set default values
                    if (e.CommandName.ToLower() == AdvancedRadGrid.InitInsertCommandName.ToLower() && e.Item.OwnerTableView.Name == "PreValues")
                    {
                        e.Canceled = true;
                        Hashtable values = new Hashtable();
                        values["IsSelected"] = false;
                        e.Item.OwnerTableView.InsertItem(values);
                    }
                    if (e.CommandName.ToLower() == AdvancedRadGrid.ExpandCollapseCommandName.ToLower())
                    {
                        e.Canceled = true;
                        return;
                    }
                    //expand or narrow custom fields
                    if (e.CommandName.ToLower() == "ExpandCustomFields".ToLower())
                    {
                        e.Item.Expanded = !e.Item.Expanded;
                        e.Item.Selected = true;
                        foreach (GridItem item in e.Item.OwnerTableView.Items)
                        {
                            if (item.Expanded && item != e.Item)
                            {
                                item.Expanded = false;
                            }
                        }
                    }
                    else if (e.CommandName.ToLower() == "ExpandPreValues".ToLower())
                    {
                        e.Item.Expanded = !e.Item.Expanded;
                        e.Item.Selected = true;
                        foreach (GridItem item in e.Item.OwnerTableView.Items)
                        {
                            if (item.Expanded && item != e.Item)
                            {
                                item.Expanded = false;
                            }
                        }
                    }
                    else if (e.CommandName.ToLower() == "CusFieldUp".ToLower())
                    {
                        long id = Convert.ToInt64(e.CommandArgument);
                        var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);
                        item.FilesTypeReference.Load();
                        long fileTypeId=item.FilesType.FileType_ID;
                        var PrevItem = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == fileTypeId && i.CusField_Order < item.CusField_Order).OrderByDescending(i => i.CusField_Order).FirstOrDefault();
                        if (PrevItem!=null)
                        {
                            long? temp = PrevItem.CusField_Order;
                            PrevItem.CusField_Order = item.CusField_Order;
                            item.CusField_Order = temp;
                            ent.SaveChanges();
                            e.Item.OwnerTableView.Rebind();
                        }
                    }
                    else if (e.CommandName.ToLower() == "CusFieldDown".ToLower())
                    {
                        long id = Convert.ToInt64(e.CommandArgument);
                        var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);
                        item.FilesTypeReference.Load();
                        long fileTypeId = item.FilesType.FileType_ID;
                        var nextitem = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == fileTypeId && i.CusField_Order > item.CusField_Order).OrderBy(i => i.CusField_Order).FirstOrDefault();
                        if(nextitem!=null)
                        {
                            long? temp = nextitem.CusField_Order;
                            nextitem.CusField_Order = item.CusField_Order;
                            item.CusField_Order = temp;
                            ent.SaveChanges();
                            e.Item.OwnerTableView.Rebind();
                        }
                    }
                    else if (e.CommandName.ToLower() == "PrevalueUP".ToLower())
                    {
                        long id = Convert.ToInt64(e.CommandArgument);
                        var item = ent.PreValues.FirstOrDefault(i => i.PreValue_ID == id);
                        item.FilesTypes_CusFieldsReference.Load();
                        long fileTypeCusFieldID = item.FilesTypes_CusFields.FT_CS_ID;
                        var PrevItem = ent.PreValues.Where(i => i.FilesTypes_CusFields.FT_CS_ID == fileTypeCusFieldID && i.PreValue_Order < item.PreValue_Order).OrderByDescending(i => i.PreValue_Order).FirstOrDefault();
                        if (PrevItem!=null)
                        {
                            long? temp = PrevItem.PreValue_Order;
                            PrevItem.PreValue_Order = item.PreValue_Order;
                            item.PreValue_Order = temp;
                            ent.SaveChanges();
                            e.Item.OwnerTableView.Rebind();
                        }
                    }
                    else if (e.CommandName.ToLower() == "PrevalueDown".ToLower())
                    {
                        long id = Convert.ToInt64(e.CommandArgument);
                        var item = ent.PreValues.FirstOrDefault(i => i.PreValue_ID == id);
                        item.FilesTypes_CusFieldsReference.Load();
                        long fileTypeCusFieldID = item.FilesTypes_CusFields.FT_CS_ID;
                        var nextitem = ent.PreValues.Where(i => i.FilesTypes_CusFields.FT_CS_ID == fileTypeCusFieldID && i.PreValue_Order > item.PreValue_Order).OrderBy(i => i.PreValue_Order).FirstOrDefault();
                        if(nextitem!=null)
                        {
                            long? temp = nextitem.PreValue_Order;
                            nextitem.PreValue_Order = item.PreValue_Order;
                            item.PreValue_Order = temp;
                            ent.SaveChanges();
                            e.Item.OwnerTableView.Rebind();
                        }
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
            }
        }
        protected void AdvancedRadGridResults_InsertCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        string code = newValues["FileType_code"].ToString();
                        string nameAr = newValues["FileTypeName_Ar"].ToString();
                        string noteAr = newValues["FileTypeNote_Ar"].ToString();
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + nameAr + noteAr);
                        ent.AddToFilesTypes(new FilesType
                        {
                            FileType_Code = code,
                            FileTypeName_Ar = nameAr,
                            FileTypeNote_Ar = noteAr,
                            FileType_UniqueText = uniquetext
                        });
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "CustomFields")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        RadDropDownList RadDropDownListCusField = ((RadDropDownList)e.Item.FindControl("RadDropDownListCusField"));
                        long? cusFieldID = null;
                        if (RadDropDownListCusField.SelectedValue != null)
                        {
                            cusFieldID = Convert.ToInt64(RadDropDownListCusField.SelectedValue);
                        }
                        long parentID = Convert.ToInt64(e.Item.OwnerTableView.ParentItem.OwnerTableView.DataKeyValues[e.Item.OwnerTableView.ParentItem.ItemIndex]["FileType_ID"]);
                        string code = newValues["FT_CS_Code"].ToString();
                        string labelAr = newValues["CusFieldLabel_Ar"].ToString();
                        string noteAr = newValues["CusFieldNote_Ar"].ToString();
                        string requiredMessageAr = newValues["RequiredMessage_AR"].ToString();
                        string regExp_AR = newValues["RegExp_AR"].ToString();
                        string regExpMessage_AR = newValues["RegExpMessage_AR"].ToString();
                        int? numberDecimalPlaces = newValues["NumberDecimalPlaces"].ToString() != "" ? Convert.ToInt32(newValues["NumberMinValue"]) : (int?)null;
                        decimal? numberMinValue = newValues["NumberMinValue"].ToString() != "" ? Convert.ToDecimal(newValues["NumberMinValue"]) :(decimal?) null;
                        decimal? numberMaxValue = newValues["NumberMaxValue"].ToString() != "" ? Convert.ToDecimal(newValues["NumberMaxValue"]) : (decimal?)null;
                        DateTime? dateMinValue = (DateTime?)newValues["DateMinValue"];
                        DateTime? dateMaxValue = (DateTime?)newValues["DateMaxValue"];
                        if (dateMinValue == DateTime.MinValue)
                        {
                            dateMinValue = null;
                        }
                        if (dateMaxValue == DateTime.MinValue)
                        {
                            dateMaxValue = null;
                        }

                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + labelAr + noteAr + requiredMessageAr + regExp_AR + regExpMessage_AR);
                        var items = ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == parentID).FilesTypes_CusFields;
                        items.Load();
                        int order = items.Count() + 1;
                        ent.FilesTypes.FirstOrDefault(i=>i.FileType_ID==parentID).FilesTypes_CusFields.Add(new FilesTypes_CusFields
                        {
                            FT_CS_Code = code,
                            CusFieldLabel_Ar = labelAr,
                            CusFieldNote_Ar = noteAr,
                            RequiredMessage_AR=requiredMessageAr,
                            RegExp_AR=regExp_AR,
                            RegExpMessage_AR=regExpMessage_AR,
                            NumberDecimalPlaces=numberDecimalPlaces,
                            NumberMinValue = numberMinValue,
                            NumberMaxValue = numberMaxValue,
                            DateMinValue = dateMinValue,
                            DateMaxValue = dateMaxValue,
                            CusField__UniqueText = uniquetext,
                            CusField_Order=order,
                            CusField=ent.CusFields.FirstOrDefault(i=>i.CusField_ID==cusFieldID)
                        });
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "PreValues")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        long parentID = Convert.ToInt64(e.Item.OwnerTableView.ParentItem.GetDataKeyValue("FT_CS_ID"));
                        RadButton RadButtonMultiInsert = ((RadButton)e.Item.FindControl("RadButtonMultiInsert"));
                        //single value
                        if (!RadButtonMultiInsert.Checked)
                        {
                            string code = newValues["PreValue_Code"].ToString();
                            string labelAr = newValues["PreValueName_Ar"].ToString();
                            string noteAr = newValues["PreValueNote_Ar"].ToString();
                            bool isSelected = Convert.ToBoolean(newValues["IsSelected"]);
                            string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + labelAr + noteAr);
                            var items = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == parentID).PreValues;
                            items.Load();
                            int order = items.Count() + 1;
                            ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == parentID).PreValues.Add(new PreValue
                            {
                                PreValue_Code = code,
                                PreValueName_Ar = labelAr,
                                PreValueNote_Ar = noteAr,
                                PreValue__UniqueText = uniquetext,
                                PreValue_Order = order,
                                IsSelected = isSelected
                            });
                            ent.SaveChanges();
                        }
                        //multi value
                        else
                        {
                            string[] code = newValues["PreValue_Code"].ToString().Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
                            string[] labelAr = newValues["PreValueName_Ar"].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            string[] noteAr = newValues["PreValueNote_Ar"].ToString().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                            bool isSelected = Convert.ToBoolean(newValues["IsSelected"]);

                            var items = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == parentID).PreValues;
                            items.Load();
                            int order = items.Count();
                            for (int i = 0; i < labelAr.Length; i++)
                            {
                                string subCode = code.Length > i ? code[i] : "";
                                string subNote = noteAr.Length > i ? code[i] : "";
                                order++;
                                string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(subCode + labelAr[i] + subNote);
                                ent.FilesTypes_CusFields.FirstOrDefault(item => item.FT_CS_ID == parentID).PreValues.Add(new PreValue
                                {
                                    PreValue_Code = subCode,
                                    PreValueName_Ar = labelAr[i],
                                    PreValueNote_Ar = subNote,
                                    PreValue__UniqueText = uniquetext,
                                    PreValue_Order = order,
                                    IsSelected = isSelected
                                });
                            }
                            ent.SaveChanges();
                        }
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                }
            }
            
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_UpdateCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    GridEditableItem editedItem = e.Item as GridEditableItem;
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FileType_ID"]);
                        string code = newValues["FileType_code"].ToString();
                        string nameAr = newValues["FileTypeName_Ar"].ToString();
                        string noteAr = newValues["FileTypeNote_Ar"].ToString();
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + nameAr + noteAr);
                        var item = ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == id);
                        item.FileType_Code = code;
                        item.FileTypeName_Ar = nameAr;
                        item.FileTypeNote_Ar = noteAr;
                        item.FileType_UniqueText = uniquetext;
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "CustomFields")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FT_CS_ID"]);
                        string code = newValues["FT_CS_Code"].ToString();
                        string labelAr = newValues["CusFieldLabel_Ar"].ToString();
                        string noteAr = newValues["CusFieldNote_Ar"].ToString();
                        string requiredMessageAr = newValues["RequiredMessage_AR"].ToString();
                        string regExp_AR = newValues["RegExp_AR"].ToString();
                        string regExpMessage_AR = newValues["RegExpMessage_AR"].ToString();
                        int? numberDecimalPlaces = newValues["NumberDecimalPlaces"].ToString() != "" ? Convert.ToInt32(newValues["NumberMinValue"]) : (int?)null;
                        decimal? numberMinValue = newValues["NumberMinValue"].ToString() != "" ? Convert.ToDecimal(newValues["NumberMinValue"]) : (decimal?)null;
                        decimal? numberMaxValue = newValues["NumberMaxValue"].ToString() != "" ? Convert.ToDecimal(newValues["NumberMaxValue"]) : (decimal?)null;
                        DateTime? dateMinValue = (DateTime?)newValues["DateMinValue"];
                        DateTime? dateMaxValue = (DateTime?)newValues["DateMaxValue"];

                        if (dateMinValue == DateTime.MinValue)
                        {
                            dateMinValue = null;
                        }
                        if (dateMaxValue == DateTime.MinValue)
                        {
                            dateMaxValue = null;
                        }


                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + labelAr + noteAr + requiredMessageAr + regExp_AR + regExpMessage_AR);
                        var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);
                        item.FT_CS_Code = code;
                        item.CusFieldLabel_Ar = labelAr;
                        item.CusFieldNote_Ar = noteAr;
                        item.RequiredMessage_AR=requiredMessageAr;
                        item.RegExp_AR=regExp_AR;
                        item.RegExpMessage_AR=regExpMessage_AR;
                        item.NumberDecimalPlaces=numberDecimalPlaces;
                        item.NumberMinValue = numberMinValue;
                        item.NumberMaxValue = numberMaxValue;
                        item.DateMinValue = dateMinValue;
                        item.DateMaxValue = dateMaxValue;
                        item.CusField__UniqueText = uniquetext;
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "PreValues")
                    {
                        Hashtable newValues = new Hashtable();
                        e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PreValue_ID"]);
                        string code = newValues["PreValue_Code"].ToString();
                        string nameAr = newValues["PreValueName_Ar"].ToString();
                        string noteAr = newValues["PreValueNote_Ar"].ToString();
                        bool isSelected = Convert.ToBoolean(newValues["IsSelected"]);
                        string uniquetext = WebHelper.Helpers.StringHelper.ToUniqueStatement(code + nameAr + noteAr);
                        var item = ent.PreValues.FirstOrDefault(i => i.PreValue_ID == id);
                        item.PreValue_Code = code;
                        item.PreValueName_Ar = nameAr;
                        item.PreValueNote_Ar = noteAr;
                        item.PreValue__UniqueText = uniquetext;
                        item.IsSelected = isSelected;
                        ent.SaveChanges();
                        this.ShowNotification("تم الحفظ بنجاح", NotificationIconType.Ok);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحفظ " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_DeleteCommand(object sender, GridCommandEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.Item.OwnerTableView.Name == "master")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FileType_ID"]);
                        ent.DeleteObject(ent.FilesTypes.FirstOrDefault(i => i.FileType_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "CustomFields")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FT_CS_ID"]);
                        ent.DeleteObject(ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                    else if (e.Item.OwnerTableView.Name == "PreValues")
                    {
                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["PreValue_ID"]);
                        ent.DeleteObject(ent.PreValues.FirstOrDefault(i => i.PreValue_ID == id));
                        ent.SaveChanges();
                        this.ShowNotification("تم الحذف بنجاح", NotificationIconType.Ok);
                    }
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي اثناء الحذف " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void AdvancedRadGridResults_ItemDataBound(object sender, GridItemEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {
                    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
                    {
                        if (e.Item.OwnerTableView.Name == "CustomFields")
                        {
                            RadDropDownList RadDropDownListCFieldType = (RadDropDownList)e.Item.FindControl("RadDropDownListCFieldType");
                            if (RadDropDownListCFieldType != null)
                            {
                                var items = ent.CusFieldsTypes.ToArray();
                                RadDropDownListCFieldType.DataSource = items;
                                RadDropDownListCFieldType.DataTextField = "CFieldTypeName_Ar";
                                RadDropDownListCFieldType.DataValueField = "CFieldType_ID";
                                RadDropDownListCFieldType.DataBind();
                                if (items.Count() > 0)
                                {
                                    if ((e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem))
                                    {
                                        RadDropDownListCFieldType.SelectedIndex = 0;
                                    }
                                    else
                                    {
                                        long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FT_CS_ID"]);
                                        var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);
                                        item.CusFieldReference.Load();
                                        item.CusField.CusFieldsTypeReference.Load();
                                        RadDropDownListCFieldType.SelectedValue = item.CusField.CusFieldsType.CFieldType_ID.ToString();
                                        RadDropDownListCFieldType.Enabled = false;
                                    }
                                }

                                RadDropDownList RadDropDownListCusField = (RadDropDownList)e.Item.FindControl("RadDropDownListCusField");
                                if (RadDropDownListCusField != null)
                                {
                                    long cfieldtypeId = Convert.ToInt64(RadDropDownListCFieldType.SelectedValue);
                                    e.Item.FindControl("ULText").Visible = cfieldtypeId == (long)CustomFieldTypeEnum.Text;
                                    e.Item.FindControl("ULNumber").Visible = cfieldtypeId == (long)CustomFieldTypeEnum.Number;
                                    e.Item.FindControl("ULDate").Visible = cfieldtypeId == (long)CustomFieldTypeEnum.Date;

                                    long FileTypeID = Convert.ToInt64(e.Item.OwnerTableView.ParentItem.GetDataKeyValue("FileType_ID"));
                                    CusField[] CusFieldsitems = ent.CusFields.Where(i => i.CusFieldsType.CFieldType_ID == cfieldtypeId).OrderBy(i => i.CusFieldName).ToArray();

                                    //if insert then exclude prevois taken custom fields
                                    if ((e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem))
                                    {
                                        var currentIDs = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == cfieldtypeId).Select(i => i.CusField.CusField_ID).ToList();
                                        CusFieldsitems = CusFieldsitems.Where(i => !currentIDs.Contains(i.CusField_ID)).ToArray();
                                    }

                                    RadDropDownListCusField.DataSource = CusFieldsitems;
                                    RadDropDownListCusField.DataTextField = "CusFieldName";
                                    RadDropDownListCusField.DataValueField = "CusField_ID";
                                    RadDropDownListCusField.DataBind();
                                    if (CusFieldsitems.Count() > 0)
                                    {
                                        if ((e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem))
                                        {
                                            RadDropDownListCusField.SelectedIndex = 0;
                                        }
                                        else
                                        {
                                            long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FT_CS_ID"]);
                                            var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);
                                            item.CusFieldReference.Load();
                                            RadDropDownListCusField.SelectedValue = item.CusField.CusField_ID.ToString();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (e.Item is GridDataItem)
                    {
                        if (e.Item.OwnerTableView.Name == "CustomFields")
                        {
                            Button ButtonPreValues = (Button)e.Item.FindControl("ButtonPreValues");
                            if (ButtonPreValues != null)
                            {
                                long id = Convert.ToInt64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["FT_CS_ID"]);
                                var item = ent.FilesTypes_CusFields.FirstOrDefault(i => i.FT_CS_ID == id);

                                item.CusFieldReference.Load();
                                if (!item.CusField.CusFieldName.ToLower().StartsWith("m") && !item.CusField.CusFieldName.ToLower().StartsWith("c"))
                                {
                                    ButtonPreValues.Enabled = false;
                                }
                            }
                        }
                    }
                }

            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                e.Canceled = true;
                return;
            }
        }
        protected void RadDropDownListCFieldType_SelectedIndexChanged(object sender, DropDownListEventArgs e)
        {
            try
            {
                using (ArchivingDataEntities ent = new ArchivingDataEntities())
                {

                    RadDropDownList ddl1 = (RadDropDownList)sender;
                    RadDropDownList ddl2 = (RadDropDownList)ddl1.NamingContainer.FindControl("RadDropDownListCusField");
                    long id=Convert.ToInt64(ddl1.SelectedValue);


                    GridEditableItem editedItem = (GridEditableItem)ddl1.NamingContainer;
                    editedItem.FindControl("ULText").Visible = id == (long)CustomFieldTypeEnum.Text;
                    editedItem.FindControl("ULNumber").Visible = id == (long)CustomFieldTypeEnum.Number;
                    editedItem.FindControl("ULDate").Visible = id == (long)CustomFieldTypeEnum.Date;

                    long FileTypeID = Convert.ToInt64(editedItem.OwnerTableView.ParentItem.GetDataKeyValue("FileType_ID"));
                    var currentIDs = ent.FilesTypes_CusFields.Where(i => i.FilesType.FileType_ID == id).Select(i => i.CusField.CusField_ID).ToList();
                    var items = ent.CusFields.Where(i => i.CusFieldsType.CFieldType_ID == id).OrderBy(i=>i.CusFieldName).ToArray().Where(i => !currentIDs.Contains(i.CusField_ID));
                    ddl2.DataSource = items;
                    ddl2.DataTextField = "CusFieldName";
                    ddl2.DataValueField = "CusField_ID";
                    if (items.Count() > 0)
                    {
                        ddl2.SelectedIndex = 0;
                    }
                    ddl2.DataBind();
                }
            }
            catch (Exception er)
            {
                this.ShowNotification("حدث الخطا التالي " + er.Message, NotificationIconType.Error);
                return;
            }
        }

    }
}